{% extends "layui/admin/base.html" %}
{% block title %}导航网站 - 用户管理{% endblock %}

{% block content %}
    <blockquote class="layui-elem-quote">
        <p><a href="/admin/v2"><i class="layui-icon layui-icon-home"></i> 首页</a>
            <i class="layui-icon layui-icon-next"></i> 用户管理</p>
    </blockquote>
    <div class="layui-panel">
        <br>
        <div class="layui-card">
            <div class="layui-card-header">
                <h1>用户管理</h1>
            </div>
            <div class="layui-card-body">
                <table id="userTable" lay-filter="userTableFilter"></table>
            </div>
        </div>
        <script type="text/html" id="toolbar">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-sm" id="addUserBtn">
                    <i class="layui-icon">&#xe654;</i> 添加用户
                </button>
                <button class="layui-btn layui-btn-sm layui-bg-blue" id="reload">
                    刷新
                    <i class="layui-icon layui-icon-down layui-font-12"></i>
                </button>
            </div>
        </script>

        <!-- 表格操作列模板 -->
        <script type="text/html" id="userTableToolbar">
            <a class="layui-btn layui-btn-xs" lay-event="view">查看</a>
            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
        </script>

        <!-- 添加用户弹窗表单 -->
        <div id="addUserModal" style="display: none; padding: 20px;">
            <form class="layui-form" id="addUserForm">
                <div class="layui-form-item">
                    <label class="layui-form-label">用户名</label>
                    <div class="layui-input-block">
                        <input type="text" name="username" required lay-verify="required" placeholder="请输入用户名"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">邮箱</label>
                    <div class="layui-input-block">
                        <input type="email" name="email" required lay-verify="required|email" placeholder="请输入邮箱"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">角色</label>
                    <div class="layui-input-block">
                        <select name="role">
                            <option value="user">普通用户</option>
                            <option value="admin">管理员</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">密码</label>
                    <div class="layui-input-block">
                        <input type="password" name="password" required lay-verify="required" placeholder="请输入密码"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit lay-filter="submitUser">提交</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

{% endblock %}

{% block scripts %}
    <script>
        layui.use(['table', 'form', 'layer'], function () {
            const table = layui.table;
            const form = layui.form;
            const layer = layui.layer;
            const $ = layui.$;

            // 初始化表格
            table.render({
                elem: '#userTable',
                page: true,
                cols: [[
                    {field: 'id', title: 'ID', width: 60},
                    {field: 'username', title: '用户名'},
                    {field: 'email', title: '邮箱'},
                    {
                        field: 'role',
                        title: '角色',
                        templet: d => d.role === 'admin'
                            ? '<span class="layui-badge layui-bg-blue">管理员</span>'
                            : '<span class="layui-badge layui-bg-gray">普通用户</span>'
                    },
                    {
                        field: 'is_deleted',
                        title: '状态',
                        width: 80,
                        templet: d => d.is_deleted
                            ? '<span class="layui-badge layui-bg-red">禁用</span>'
                            : '<span class="layui-badge layui-bg-green">正常</span>'
                    },
                    {field: 'created_at', title: '创建时间'},
                    {field: 'updated_at', title: '更新时间'},
                    {fixed: 'right', title: '操作', toolbar: '#userTableToolbar', width: 140}
                ]],
                toolbar: '#toolbar',
                defaultToolbar: ['filter', 'exports', 'print', { // 右上角工具图标
                    title: '提示',
                    layEvent: 'LAYTABLE_TIPS',
                    icon: 'layui-icon-tips',
                    onClick: function (obj) { // 2.9.12+
                        layer.alert('自定义工具栏图标按钮');
                    }
                }],
                loading: true,
                text: {
                    none: '暂无数据'
                }
            });

            // 加载分类数据
            function loadUserData() {
                $.ajax({
                    url: '/api/users/',
                    type: 'GET',
                    dataType: 'json',
                    headers: {
                        'Authorization': 'Bearer ' + localStorage.getItem('token')
                    },
                    success: function (res) {
                        if (res.code === 0) {
                            table.reload('userTable', {
                                data: res.data
                            });
                        } else {
                            layer.msg(res.msg || '加载失败', {icon: 2});
                        }
                    },
                    error: function (xhr, status, error) {
                        layer.msg('请求失败: ' + error, {icon: 2});
                    }
                });
            }

            loadUserData();  // 初始加载
            // 打开添加用户弹窗
            $('#addUserBtn').on('click', function () {
                layer.open({
                    type: 1,
                    title: '添加用户',
                    area: ['500px', '400px'],
                    content: $('#addUserModal')
                });

            });

            // 表单提交事件
            form.on('submit(submitUser)', function (data) {
                $.ajax({
                    url: '/api/users/',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(data.field),
                    success: function (res) {
                        if (res.code === 0) {
                            layer.closeAll();
                            layer.msg(res.msg);
                            loadUserData();
                        } else {
                            layer.alert(res.msg || '添加失败', {icon: 2});
                        }
                    },
                    error: function () {
                        layer.alert('网络错误或接口异常', {icon: 2});
                    }
                });
                return false;
            });

            // 表格操作事件
            table.on('tool(userTableFilter)', function (obj) {
                const data = obj.data;
                if (obj.event === 'view') {
                    layer.open({
                        type: 1,
                        title: '查看用户',
                        area: ['400px', '300px'],
                        content: `<div style="padding: 20px;">
                            <p><strong>用户名：</strong>${data.username}</p>
                            <p><strong>邮箱：</strong>${data.email}</p>
                            <p><strong>角色：</strong>${data.role}</p>
                            <p><strong>状态：</strong>${data.is_deleted ? '禁用' : '正常'}</p>
                        </div>`
                    });
                } else if (obj.event === 'delete') {
                    layer.confirm('确定要删除该用户吗？', function (index) {
                        $.ajax({
                            url: `/api/users/${data.id}`,
                            type: 'DELETE',
                            success: function (res) {
                                if (res.code === 0) {
                                    layer.msg(res.msg);
                                    table.reload('userTable');
                                } else {
                                    layer.alert(res.msg || '删除失败', {icon: 2});
                                }
                            },
                            error: function () {
                                layer.alert('网络错误或接口异常', {icon: 2});
                            }
                        });
                        layer.close(index);
                    });
                }
            });
        });
    </script>
{% endblock %}
